import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import "../components"

/**
 * 仪表列表页
 * 支持搜索、筛选、排序
 * 
 * 布局优化（1024×768分辨率）：
 * - 可用区域：794px宽 × 738px高
 * - 工具栏：90px（压缩，标题+搜索）
 * - 电表列表：剩余空间（约638px，最大化）
 * - 主间距：10px × 2 = 20px
 */
Item {
    id: root

    // 私有属性
    property int selectedMeterId: -1
    property string searchText: ""
    property int filterBusId: 0  // 0=全部, 1/2/3=配电室A/B/C
    property int filterStatus: 0 // 0=全部, 1=在线, 2=离线
    property int sortMode: 0     // 0=按ID, 1=按名称, 2=按电压, 3=按电流

    // 刷新定时器
    Timer {
        interval: 1000
        running: true
        repeat: true
        onTriggered: {
            // 模型会自动刷新，这里可以做其他更新
        }
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 10

        // 页面标题和工具栏
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 95  // 稍微增加高度以适应更大的字体
            Layout.minimumHeight: 95
            color: "white"
            radius: 6

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 8

                // 标题
                Text {
                    text: "📋 仪表列表"
                    font.pixelSize: 16
                    font.bold: true
                    color: "#2c3e50"
                }

                // 搜索和筛选工具栏（压缩）
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 8

                    // 搜索框
                    Rectangle {
                        Layout.preferredWidth: 240  // 增加宽度以便更舒适地输入
                        height: 32  // 与其他控件高度保持一致
                        color: "#f8f9fa"
                        radius: 3
                        border.width: 1
                        border.color: searchField.activeFocus ? "#3498db" : "#dfe6e9"

                        RowLayout {
                            anchors.fill: parent
                            anchors.margins: 6
                            spacing: 6

                            Text {
                                text: "🔍"
                                font.pixelSize: 14
                            }

                            TextField {
                                id: searchField
                                Layout.fillWidth: true
                                placeholderText: "搜索电表..."
                                font.pixelSize: 12  // 增加字体大小以提高可读性
                                background: Rectangle { color: "transparent" }
                                
                                onTextChanged: {
                                    root.searchText = text
                                    filterMeters()
                                }
                            }

                            Button {
                                visible: searchField.text.length > 0
                                text: "×"
                                font.pixelSize: 14
                                flat: true
                                implicitHeight: 20
                                onClicked: {
                                    searchField.text = ""
                                }
                            }
                        }
                    }

                    // 配电室筛选
                    ComboBox {
                        id: busFilterCombo
                        Layout.preferredWidth: 110  // 增加宽度以容纳"全部配电室"
                        implicitHeight: 32  // 与搜索框高度保持一致
                        model: ["全部配电室", "配电室A", "配电室B", "配电室C"]
                        font.pixelSize: 11  // 稍微增加字体大小以提高可读性
                        
                        onCurrentIndexChanged: {
                            root.filterBusId = currentIndex
                            applyFilters()
                        }
                    }

                    // 状态筛选
                    ComboBox {
                        id: statusFilterCombo
                        Layout.preferredWidth: 95  // 增加宽度以容纳"全部状态"
                        implicitHeight: 32  // 与搜索框高度保持一致
                        model: ["全部状态", "在线", "离线"]
                        font.pixelSize: 11  // 稍微增加字体大小以提高可读性
                        
                        onCurrentIndexChanged: {
                            root.filterStatus = currentIndex
                            applyFilters()
                        }
                    }

                    // 排序方式
                    ComboBox {
                        id: sortCombo
                        Layout.preferredWidth: 110  // 增加宽度以容纳"按电压排序"等文本
                        implicitHeight: 32  // 与搜索框高度保持一致
                        model: ["按ID排序", "按名称排序", "按电压排序", "按电流排序"]
                        font.pixelSize: 11  // 稍微增加字体大小以提高可读性
                        
                        onCurrentIndexChanged: {
                            root.sortMode = currentIndex
                            sortMeters()
                        }
                    }

                    Item {
                        Layout.fillWidth: true
                    }

                    // 统计信息（压缩）
                    Row {
                        spacing: 6

                        Rectangle {
                            width: 65  // 增加宽度以容纳三位数
                            height: 32  // 稍微增加高度
                            radius: 3
                            color: "#e8f5e9"

                            Column {
                                anchors.centerIn: parent
                                spacing: 2

                                Text {
                                    text: "在线"
                                    font.pixelSize: 10  // 增加字体大小
                                    color: "#27ae60"
                                    anchors.horizontalCenter: parent.horizontalCenter
                                }

                                Text {
                                    text: deviceManager ? deviceManager.onlineCount : 0
                                    font.pixelSize: 13  // 增加数字大小
                                    font.bold: true
                                    color: "#27ae60"
                                    anchors.horizontalCenter: parent.horizontalCenter
                                }
                            }
                        }

                        Rectangle {
                            width: 65  // 增加宽度以容纳三位数
                            height: 32  // 稍微增加高度
                            radius: 3
                            color: "#ffebee"

                            Column {
                                anchors.centerIn: parent
                                spacing: 2

                                Text {
                                    text: "离线"
                                    font.pixelSize: 10  // 增加字体大小
                                    color: "#e74c3c"
                                    anchors.horizontalCenter: parent.horizontalCenter
                                }

                                Text {
                                    text: deviceManager ? deviceManager.offlineCount : 0
                                    font.pixelSize: 13  // 增加数字大小
                                    font.bold: true
                                    color: "#e74c3c"
                                    anchors.horizontalCenter: parent.horizontalCenter
                                }
                            }
                        }

                        Rectangle {
                            width: 65  // 增加宽度以容纳三位数
                            height: 32  // 稍微增加高度
                            radius: 3
                            color: "#e3f2fd"

                            Column {
                                anchors.centerIn: parent
                                spacing: 2

                                Text {
                                    text: "总计"
                                    font.pixelSize: 10  // 增加字体大小
                                    color: "#3498db"
                                    anchors.horizontalCenter: parent.horizontalCenter
                                }

                                Text {
                                    text: deviceManager ? deviceManager.totalCount : 0
                                    font.pixelSize: 13  // 增加数字大小
                                    font.bold: true
                                    color: "#3498db"
                                    anchors.horizontalCenter: parent.horizontalCenter
                                }
                            }
                        }
                    }
                }
            }
        }

        // 电表列表（最大化剩余空间）
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
            radius: 6

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 8

                // 列表标题栏（压缩）
                RowLayout {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 28

                    Text {
                        text: "电表列表 (" + (meterListView.count) + " 台)"
                        font.pixelSize: 14
                        font.bold: true
                        color: "#2c3e50"
                    }

                    Item {
                        Layout.fillWidth: true
                    }

                    // 视图切换按钮（压缩）
                    Row {
                        spacing: 4

                        Button {
                            id: gridViewBtn
                            text: "⊞"
                            font.pixelSize: 14
                            implicitWidth: 32
                            implicitHeight: 26
                            checkable: true
                            checked: true
                            onClicked: {
                                listViewBtn.checked = false
                                checked = true
                            }
                        }

                        Button {
                            id: listViewBtn
                            text: "☰"
                            font.pixelSize: 14
                            implicitWidth: 32
                            implicitHeight: 26
                            checkable: true
                            onClicked: {
                                gridViewBtn.checked = false
                                checked = true
                            }
                        }
                    }
                }

                // 电表卡片网格视图
                ScrollView {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true
                    visible: gridViewBtn.checked
                    contentWidth: availableWidth

                    GridLayout {
                        width: parent.width
                        columns: Math.max(1, Math.floor(width / 280))
                        rowSpacing: 12
                        columnSpacing: 12

                        Repeater {
                            id: meterListView
                            model: meterModel

                            MeterCard {
                                Layout.fillWidth: true
                                Layout.preferredHeight: 190
                                Layout.minimumWidth: 250
                                Layout.maximumWidth: 400

                                meterId: model.meterId
                                meterName: model.name
                                location: model.location
                                online: model.online
                                ua: model.ua
                                ub: model.ub
                                uc: model.uc
                                ia: model.ia
                                ib: model.ib
                                ic: model.ic
                                averageVoltage: model.averageVoltage
                                averageCurrent: model.averageCurrent
                                totalPower: model.totalPower

                                // 点击卡片打开详情页
                                onClicked: {
                                    openMeterDetail(model.meterId)
                                }
                            }
                        }
                    }
                }

                // 列表视图
                ScrollView {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true
                    visible: listViewBtn.checked

                    ListView {
                        id: meterTableView
                        model: meterModel
                        spacing: 2

                        header: Rectangle {
                            width: meterTableView.width
                            height: 40
                            color: "#f8f9fa"

                            Row {
                                anchors.fill: parent
                                anchors.margins: 10
                                spacing: 10

                                Text {
                                    width: 60
                                    text: "ID"
                                    font.pixelSize: 12
                                    font.bold: true
                                    color: "#7f8c8d"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 100
                                    text: "名称"
                                    font.pixelSize: 12
                                    font.bold: true
                                    color: "#7f8c8d"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 150
                                    text: "位置"
                                    font.pixelSize: 12
                                    font.bold: true
                                    color: "#7f8c8d"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 80
                                    text: "状态"
                                    font.pixelSize: 12
                                    font.bold: true
                                    color: "#7f8c8d"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 100
                                    text: "平均电压(V)"
                                    font.pixelSize: 12
                                    font.bold: true
                                    color: "#7f8c8d"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 100
                                    text: "平均电流(A)"
                                    font.pixelSize: 12
                                    font.bold: true
                                    color: "#7f8c8d"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 100
                                    text: "总功率(kW)"
                                    font.pixelSize: 12
                                    font.bold: true
                                    color: "#7f8c8d"
                                    verticalAlignment: Text.AlignVCenter
                                }
                            }
                        }

                        delegate: Rectangle {
                            width: meterTableView.width
                            height: 50
                            color: index % 2 === 0 ? "white" : "#f8f9fa"

                            MouseArea {
                                anchors.fill: parent
                                hoverEnabled: true
                                cursorShape: Qt.PointingHandCursor

                                onEntered: {
                                    parent.color = "#e3f2fd"
                                }

                                onExited: {
                                    parent.color = index % 2 === 0 ? "white" : "#f8f9fa"
                                }

                                onClicked: {
                                    openMeterDetail(model.meterId)
                                }
                            }

                            Row {
                                anchors.fill: parent
                                anchors.margins: 10
                                spacing: 10

                                Text {
                                    width: 60
                                    text: "#" + model.meterId
                                    font.pixelSize: 13
                                    color: "#2c3e50"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 100
                                    text: model.name
                                    font.pixelSize: 13
                                    color: "#2c3e50"
                                    verticalAlignment: Text.AlignVCenter
                                    elide: Text.ElideRight
                                }

                                Text {
                                    width: 150
                                    text: model.location
                                    font.pixelSize: 13
                                    color: "#7f8c8d"
                                    verticalAlignment: Text.AlignVCenter
                                    elide: Text.ElideRight
                                }

                                Rectangle {
                                    width: 80
                                    height: 24
                                    radius: 4
                                    color: model.online ? "#27ae60" : "#e74c3c"
                                    anchors.verticalCenter: parent.verticalCenter

                                    Text {
                                        anchors.centerIn: parent
                                        text: model.online ? "在线" : "离线"
                                        font.pixelSize: 11
                                        font.bold: true
                                        color: "white"
                                    }
                                }

                                Text {
                                    width: 100
                                    text: model.averageVoltage.toFixed(1)
                                    font.pixelSize: 13
                                    color: "#2c3e50"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 100
                                    text: model.averageCurrent.toFixed(2)
                                    font.pixelSize: 13
                                    color: "#2c3e50"
                                    verticalAlignment: Text.AlignVCenter
                                }

                                Text {
                                    width: 100
                                    text: (model.totalPower / 1000).toFixed(2)
                                    font.pixelSize: 13
                                    color: "#2c3e50"
                                    verticalAlignment: Text.AlignVCenter
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // 筛选电表
    function filterMeters() {
        // 搜索功能（后续可以在模型中实现）
        console.log("搜索:", root.searchText)
    }

    // 应用筛选
    function applyFilters() {
        if (!meterModel) return

        // FilterMode枚举值: ShowAll=0, ShowOnline=1, ShowOffline=2, ShowByBus=3
        // 根据配电室筛选
        if (root.filterBusId > 0) {
            meterModel.filterMode = 3  // ShowByBus
            meterModel.filterBusId = root.filterBusId
        } else if (root.filterStatus === 1) {
            meterModel.filterMode = 1  // ShowOnline
        } else if (root.filterStatus === 2) {
            meterModel.filterMode = 2  // ShowOffline
        } else {
            meterModel.filterMode = 0  // ShowAll
        }

        meterModel.refresh()
    }

    // 排序电表
    function sortMeters() {
        // 排序功能（后续可以在模型中实现）
        console.log("排序模式:", root.sortMode)
    }

    // 打开电表详情页
    function openMeterDetail(meterId) {
        console.log("==== MeterListPage: 打开电表详情 ====")
        console.log("MeterListPage: meterId=", meterId)
        console.log("MeterListPage: mainWindow=", typeof mainWindow !== 'undefined' ? mainWindow : "undefined")
        
        root.selectedMeterId = meterId
        
        try {
            console.log("MeterListPage: 调用 mainWindow.openMeterDetail()...")
            // 调用主窗口的全局函数
            mainWindow.openMeterDetail(meterId)
            console.log("MeterListPage: 调用完成")
        } catch (e) {
            console.error("MeterListPage: openMeterDetail 出错:", e)
            console.error("MeterListPage: 错误堆栈:", e.stack)
        }
    }

    // 监听模型的filterBusId变化，同步更新UI
    Connections {
        target: meterModel
        
        function onFilterBusIdChanged() {
            if (meterModel && meterModel.filterMode === 3) {
                // 同步更新配电室筛选下拉框
                busFilterCombo.currentIndex = meterModel.filterBusId
            }
        }
    }

    Component.onCompleted: {
        console.log("MeterListPage loaded")
    }
}

